package com.yc.videoview;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.app.Context;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import java.util.ArrayList;
import java.util.List;


/**
 * <pre>
 *     @author yangchong
 *     blog  : https://github.com/yangchong211
 *     time  : 2018/2/10
 *     desc  : 用于在内部自动申请权限
 *     revise:
 * </pre>
 */
public class PermissionActivity extends AbilitySlice {
    private static List<PermissionListener> mPermissionListenerList;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        requestAlertWindowPermission();
    }

    private void requestAlertWindowPermission() {

        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
            .withUri(Uri.getUriFromParts("package", this.getBundleName(), null))
            // 指示启动显示指定应用程序详细信息的Page能力的操作。
            .withAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS)
            .withFlags(Intent.FLAG_ABILITY_NEW_MISSION)
            .build();
        intent.setOperation(operation);
        startAbility(intent, 10);
    }


    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        if (WindowUtil.hasPermission(this)) {
            mPermissionListener.onSuccess();
        } else {
            mPermissionListener.onFail();
        }
    }

    static synchronized void request(Context context, PermissionListener permissionListener) {
        if (mPermissionListenerList == null) {
            mPermissionListenerList = new ArrayList<>();
            mPermissionListener = new PermissionListener() {
                @Override
                public void onSuccess() {
                    for (PermissionListener listener : mPermissionListenerList) {
                        listener.onSuccess();
                    }
                }

                @Override
                public void onFail() {
                    for (PermissionListener listener : mPermissionListenerList) {
                        listener.onFail();
                    }
                }
            };
            Intent intent = new Intent();
            intent.setOperation(new Intent.OperationBuilder()
                .withBundleName(context.getBundleName())
                .withAbilityName(PermissionActivity.class.getName())
                // .withFlags(Intent.NE)
                .build());
            context.startAbility(intent, 0);
        }
        mPermissionListenerList.add(permissionListener);
    }


    private static PermissionListener mPermissionListener;

    public interface PermissionListener {
        /**
         * 成功
         */
        void onSuccess();

        /**
         * 失败
         */
        void onFail();
    }
}
